package org.xbmc.android.xbmcremote;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;

public class WifiStateReceiver extends BroadcastReceiver {

	private static String bssId = "";
	@Override
	public void onReceive(Context context, Intent intent) {
		XBMCApplication oXBMCApplication = (XBMCApplication)context.getApplicationContext();
		if(oXBMCApplication==null)
			return;
		
		String action = intent.getAction();
		System.err.println("MYRECEIVER: "+action);
		if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
			System.out.println("WIFI-STATE:"+intent.getAction().toString());
			int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
			System.out.println("WIFI-STATE:"+wifiState);
			if(wifiState == WifiManager.WIFI_STATE_DISABLED)
				oXBMCApplication.setWifiConnected(false, null);
			
		} else if (action.equals(WifiManager.NETWORK_IDS_CHANGED_ACTION)) {	
			
		} else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
			
			System.out.println("NETW-STATE:"+intent.getAction().toString());
			String bssId = intent.getStringExtra(WifiManager.EXTRA_BSSID);
			if(bssId!=null)
				WifiStateReceiver.bssId = bssId;
			
			NetworkInfo networkInfo = (NetworkInfo)intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
			if(networkInfo.getState()==State.CONNECTED)
			{
				String ssId = oXBMCApplication.getSSIDfromBSSID(WifiStateReceiver.bssId);
				oXBMCApplication.setWifiConnected(true, ssId);
			}
			else
				oXBMCApplication.setWifiConnected(false, null);
			
			System.out.println("NETW-STATE: Connected: "+networkInfo.isConnected());
			System.out.println("NETW-STATE: "+networkInfo.getState().toString());
			System.out.println("NETW-STATE: "+networkInfo.getDetailedState().toString());
			System.out.println("NETW-STATE: BSSID: "+bssId);
			System.out.println("NETW-STATE: TypeName: "+networkInfo.getTypeName());
			System.out.println("NETW-STATE: Type: "+networkInfo.getType());
			
		}
	}

}
